package com.grj.service.gateway.filter;


import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import common.filter.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 14505
 */
@Component
@Slf4j
public class AuthFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header("ip", Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostString())
                .build();
        ServerHttpResponse response = exchange.getResponse();

        if(request.getURI().getPath().contains("/login")){
            return chain.filter(exchange);
        }


        if(request.getURI().getPath().contains("/article")){
            return chain.filter(exchange);
        }



        String token = request.getHeaders().getFirst("token");
        if(token==null || StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return writeResponse(exchange.getResponse(),500,"token不存在");
        }


        token = token.replaceAll("Bearer ", "");
        if(!JWTUtil.verify(token, "1234".getBytes())) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return writeResponse(exchange.getResponse(),500,"token不存在");
        }
        System.out.println("ok");

        final JWT jwt = JWTUtil.parseToken(token);
        jwt.getHeader(JWTHeader.TYPE);

        request.mutate().header("uid",jwt.getPayload("uid").toString()).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("uid", Integer.parseInt("123"));
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
            }
        };

        System.out.println(JWTUtil.createToken(map, "1234".getBytes()));
    }


    protected Mono<Void> writeResponse(ServerHttpResponse response, Integer code, String msg) {
        Result<Object> result = Result.fail(code, msg);
        String json = JSONUtil.toJsonStr(result);
        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
